package com.ruoyi.yuyuan.Service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.yuyuan.DTO.UserDTO;
import com.ruoyi.yuyuan.Utils.*;
import com.ruoyi.yuyuan.DTO.Result;
import com.ruoyi.yuyuan.Entity.*;
import com.ruoyi.yuyuan.Mapper.UserMapper;
import com.ruoyi.yuyuan.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.yuyuan.Utils.RedisConstants.LOGIN_USER_TOKEN_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private TokenGenerator tokenGenerator;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MailUtil mailUtil;

    @Override
    public Result WXLogin(String code, String userName) {
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appid + secret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");

        // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",openid);
        User user = getOne(queryWrapper);

        if (user == null) {
            // 用户信息入库
            user = new User();
            user.setId(idGenerator.nextUserId());
            user.setOpenId(openid);
            user.setName(userName);
            user.setFans(0);
            user.setFollowee(0);
            user.setBirthday(LocalDateTime.now());
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            // openid 作为密码
            user.setPassword(openid);
            save(user);
        }
        String token = tokenGenerator.getToken(user, sessionKey);

        UserDTO userDTO = new UserDTO(user.getId(),user.getName(),user.getIcon(),user.getPassword());

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        Random random = new Random();
        //存储Redis，设置过期时间
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_TOKEN_KEY + user.getId(), userMap);
        stringRedisTemplate.expire(LOGIN_USER_TOKEN_KEY + user.getId(),
                10060 + random.nextInt(20), TimeUnit.MINUTES);

        return Result.ok(token);
    }
    /**
     * 登出，移除token记录
     * @param authorization token
     * @return 结果
     */
    @Override
    public Result logOut(String authorization) {
        System.out.println("authorization:"+authorization);
        stringRedisTemplate.delete(LOGIN_USER_TOKEN_KEY+authorization);
        UserHolder.removeUser();
        return Result.ok();
    }
    /**
     * 获取当前用户信息
     * @return 结果信息
     */
    @Override
    public Result getMe() {
        Long userId = UserHolder.getUser().getId();
        //查询数据库获取全部信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.fail("用户不存在!");
        }
        UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class);
        //处理头像链接
        userInfo.handlerImgs();
        return Result.ok(userInfo);
    }
    /**
     * 获取指定用户信息
     * @param userId 用户id
     * @return 结果信息
     */
    @Override
    public Result getOther(Long userId) {
        User user = userMapper.selectById(userId);
        user.setPassword("");
        UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class);
        //处理头像链接
        userInfo.handlerImgs();
        return Result.ok(userInfo);
    }
    /**
     * 发送问题反馈邮件
     * @param issue 实体类
     * @return 结果
     */
    @Override
    public Result sendIssue(Issue issue) {
        if(issue.getFiles().isEmpty()){
            mailUtil.sendSimpleMail(issue.getTitle(),issue.getContext());
            return Result.ok();
        }
        String[] filesStr = StrUtil.splitToArray(issue.getFiles(), ',');
        List<File> files = new ArrayList<>();
        for (String s : filesStr) {
            files.add(new File(s));
        }
        mailUtil.sendAttachFileMail(issue.getTitle(),issue.getContext(),files);
        return Result.ok();
    }
}
